package logic

import (
	"cart_srv/cache"
	"cart_srv/cart"
	"cart_srv/internal/svc"
	"cart_srv/models"
	"context"
	"errors"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *cart.AddCartRequest) (*cart.AddCartResponse, error) {
	// todo: add your logic here and delete this line

	//添加购物车前判断商品是否存在
	var g models.Goods
	g.ID = uint(in.GoodsId)
	err := g.ShowGoods()
	if err != nil {
		logx.Error("购物添加失败:商品详情查找失败", err)
		return nil, err
	}
	if g.ID == 0 {
		logx.Error("购物添加失败:", errors.New("商品不存在"))
		return nil, errors.New("商品不存在")
	}
	if g.Status != 1 {
		logx.Error("购物添加失败:", errors.New("商品审核中或已下架"))
		return nil, errors.New("商品审核中或已下架")
	}

	//判断商品库粗暴是否存在 (充足)
	if g.Stock < int(in.Num) {
		logx.Error("购物添加失败:", errors.New("商品库存不足"))
		return nil, errors.New("商品库存不足")
	}

	//判断购物车内是否存在商品
	if cache.ExistsCart(in.UserId, in.GoodsId) {
		err = cache.UpdateCartNum(in.UserId, in.GoodsId, in.Num)
	} else {
		//添加商品进购物车
		goodsMap := map[string]interface{}{
			"Title": g.Title,
			"Price": g.Price,
			"Num":   in.Num,
		}
		err = cache.AddCart(in.UserId, in.GoodsId, goodsMap)
		if err != nil {
			logx.Error("购物添加失败:", err)
			return nil, err
		}
	}

	return &cart.AddCartResponse{}, nil
}
